<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="消息提示的文案" show-icon type="info" center :closable="false"></el-alert>
      <el-steps :active="activeNum - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs -->
      <el-form
        :model="addForm"
        label-position="top"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-tabs
          tab-position="left"
          v-model="activeNum"
          :before-leave="beforeLeaveHandle"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" type="number" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" type="number" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择框 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                expandTrigger="hover"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :headers='headerObj'
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button class="addBtn" type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
  title="图片预览"
  :visible.sync="imgPreviewDialogVisible"
  width="50%">
  <img class="imgPreview" :src="previewPath" alt="">
</el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      upLoadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      activeNum: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 图片数组
        pics: [],
        // 商品描述
        goods_introduce: '',
        // 级联选择框选中的分类id
        goods_cat: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '商品名称不能为空', tigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格不能为空', tigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量不能为空', tigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空', tigger: 'blur' }
        ],
        goods_cat: [
          {
            required: true,
            message: '请选择商品分类',
            tigger: 'blur',
            type: 'array'
          }
        ]
      },
      // 商品分类数据列表
      cateList: [],
      // 级联选择框配置对象
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTabData: [],
      // 上传图片列表
      fileList: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      imgPreviewDialogVisible: false,
      previewPath: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.cateList = res.data
      this.$message.success('获取商品分类列表成功')
      console.log(this.cateList)
    },
    handleChange() {
      // console.log(...this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 切换tabs之前触发
    beforeLeaveHandle(activeTab, oldActiveTab) {
      // activeTab 即将进入的标签页
      // oldActiveTab 即将离开的标签页
      if (oldActiveTab === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    async tabClicked() {
      if (this.activeNum === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.getCateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数列表失败')
        }
        console.log(res.data)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(',')
        })
        console.log(res.data)
        this.manyTableData = res.data
      } else if (this.activeNum === '2') {
        const {
          data: res
        } = await this.$http.get(`categories/${this.getCateId}/attributes`, {
          params: { sel: 'only' }
        })
        console.log(res.data)
        this.onlyTabData = res.data
      }
    },
    // 图片预览
    handlePreview(file) {
      console.log(file)
      // this.previewPath = file.response.data.url
      this.previewPath = file.response.data.url
      console.log(this.previewPath)
      this.imgPreviewDialogVisible = true
    },
    // 删除图片
    handleRemove(files) {
      console.log(files)
      // 1.获取将要删除的图片的临时路径
      const pathStr = files.response.data.tmp_path
      console.log(pathStr)
      // 2.从 pics 数组中，找到这个图片对应的索引值
      const index = this.addForm.pics.findIndex(item => {
        console.log(item)
        return item.pic === pathStr
      })
      this.addForm.pics.splice(index, 1)

      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics数组中移除
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      console.log(response)
      // 1. 拼接得到一个图片信息对象
      const picInfo = {
        pic: response.data.tmp_path
      }
      // 2. 将图片信息对象，push到pics数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 监听图片预览关闭事件
    handleClose() {},
    add() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 执行添加业务
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newObj)
        })
        // 处理静态属性
        this.onlyTabData.forEach(item => {
          const newObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newObj)
        })
        console.log(this.addForm)
        form.attrs = this.addForm.attrs
        console.log(form)
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    getCateId() {
      if (this.addForm.goods_cat.length !== 3) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.addForm.goods_cat = []
        return false
      }
      return this.addForm.goods_cat[2]
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 300px;
}
.el-checkbox {
  margin: 0 15px 0 0 !important;
}
.imgPreview {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
